<template>
  <div class="history-view">
    <h2>浏览历史</h2>
    <el-table
      v-loading="loading"
      :data="browseHistory"
      style="width: 100%"
      max-height="600">
      <el-table-column
        prop="productName"
        label="商品名称"
        min-width="200">
        <template #default="scope">
          <el-link type="primary" @click="goToProductDetail(scope.row.productId)">
            {{ scope.row.productName || '未知商品' }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="浏览时间"
        min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import InteractionService from '@/Services/InteractionService'
import ProductService from '@/Services/ProductService'

export default {
  name: 'HistoryView',
  data() {
    return {
      loading: false,
      browseHistory: [],
      userId: null
    }
  },
  created() {
    this.userId = this.getUserIdFromToken()
    if (this.userId) {
      this.loadBrowseHistory()
    } else {
      this.$message.error('请先登录')
    }
  },
  methods: {
    getUserIdFromToken() {
      const token = localStorage.getItem('token')
      if (!token) return null
      try {
        const payload = JSON.parse(atob(token.split('.')[1]))
        return payload.userId || payload.id || payload.nameid || payload.sub || payload["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]
      } catch (e) {
        return null
      }
    },
    async loadBrowseHistory() {
      try {
        this.loading = true
        const response = await InteractionService.GetUserInteractions(this.userId)
        let list = []
        if (Array.isArray(response.data)) {
          list = response.data
        } else if (Array.isArray(response.data?.$values)) {
          list = response.data.$values
        } else if (typeof response.data === 'object' && response.data !== null) {
          list = Object.values(response.data)
        }
        // 只保留type=2的浏览记录
        list = list.filter(item => item.type === 2)
        // 批量查商品名
        for (const item of list) {
          try {
            const res = await ProductService.GetById(item.productId)
            item.productName = res?.data?.title || item.productId
          } catch {
            item.productName = item.productId
          }
        }
        // 按时间倒序
        this.browseHistory = list.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
      } catch (error) {
        this.$message.error('获取浏览历史失败')
        console.error('获取浏览历史失败:', error)
      } finally {
        this.loading = false
      }
    },
    formatDate(date) {
      return new Date(date).toLocaleString()
    },
    goToProductDetail(productId) {
      this.$router.push(`/product/${productId}`)
    }
  }
}
</script>

<style scoped>
.history-view {
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 40px 20px;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}
h2 {
  color: #333;
  font-size: 28px;
  margin-bottom: 20px;
  width: 100%;
  text-align: left;
}
</style> 